﻿namespace Alkitab
{
    using Alkitab.Language;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;

    public partial class Bacaan : PhoneApplicationPage
    {
        #region Fields

        public static ObservableCollection<int> matchedIndex = new ObservableCollection<int>();
        public static bool needRefresh = false;
        public static ObservableCollection<AyatAlkitab> tmp = new ObservableCollection<AyatAlkitab>();

        // Variabel
        private int ijudul;

        private String judul;
        private int parallelOn = -1;
        private int x = 0;

        #endregion Fields

        #region Constructors

        // End of Variabel
        public Bacaan()
        {
            InitializeComponent();
            BuildApplicationBar();
            pigiKe.Text = Labels.textBox_InputVerse;
            searchBox.Text = Labels.textBox_InputText;
            needRefresh = true;

            if (Globals.terjemahanlamakah) judul = Globals.daftarBukuA[Globals.nobuku - 1]; else judul = Globals.daftarBukuN[Globals.nobuku - 1];

            bacaan.Visibility = Visibility.Visible;

            bacaan.FontSize = (int)Globals.Settingan["fontsize?"];

            musterTextBox.FontFamily = bacaan.FontFamily;
            musterTextBox.FontStyle = bacaan.FontStyle;
            musterTextBox.FontWeight = bacaan.FontWeight;
            musterTextBox.FontSize = bacaan.FontSize;

            //set Judul
            PageTitle.Text = judul + " " + Globals.nopasal;

            if (Globals.terjemahanlamakah) ijudul = Globals.nobuku; else ijudul = Globals.nobuku + 39;

            if ((int)Globals.Settingan["judulvisible?"] == 0) PageTitle.Visibility = Visibility.Collapsed; else PageTitle.Visibility = Visibility.Visible;
        }

        #endregion Constructors

        #region Methods

        public static string breakStringWithIndentation(string input, string indent)
        {
            string endResult = indent;
            /*
            List<String> result = new List<String>();
            result.Add(indent);

            string[] words = input.Split(' ');
            for (int i = 0; i < words.Length; i++)
            {
                int resultPointer = 0;
                string tempString = result[resultPointer] + words[i] + " ";
                musterTextBox.Text = tempString;
                if (musterTextBox.Width > bacaan.Width)
                {
                    resultPointer++;
                    result.Add(indent + words[i] + " ");
                }
                else
                {
                    result[resultPointer] = tempString;
                }
            }
            for (int j = 0; j < result.Count; j++)
            {
                endResult = endResult + result[j];
            }*/
            int limited = 4;
            int counter = 0;
            for (int j = 0; j < input.Length; j++)
            {
                endResult = endResult + input[j];

                if (input[j].Equals(' ') || input[j].Equals('-'))
                {
                    counter++;
                    if (counter == limited)
                    {
                        endResult = endResult + indent;
                        counter = 0;
                    }
                }
            }
            return endResult;
        }

        public static String prosesMazmurAyat(String input)
        {
            if ((bool)Globals.Settingan["mazmurOn?"])
            {
                input = input.Replace("@@@0", "@@");
                input = input.Replace("@@@1", "@@");
                input = input.Replace("@@@2", "@@");
                input = input.Replace("@@@8", "@@");
                string result = "";
                int startString = -1;
                string indent = "";
                bool foundAt = false;
                bool readyToCut = false;
                for (int i = 0; i < input.Length; i++)
                {
                    string substring = "";
                    if (input[i].Equals('@') || i == (input.Length - 1))
                    {
                        foundAt = !foundAt;
                        if (readyToCut)
                        {
                            substring = breakStringWithIndentation(input.Substring(startString, i - startString), indent);
                            readyToCut = false;
                        }
                    }
                    else
                    {
                        if (foundAt)
                        {
                            if (input[i].Equals('1'))
                            {
                                startString = i + 1;
                                indent = "\n     ";
                                readyToCut = true;
                            }
                            if (input[i].Equals('2'))
                            {
                                startString = i + 1;
                                indent = "\n          ";
                                readyToCut = true;
                            }
                            if (input[i].Equals('0')) substring = "\n";
                            if (input[i].Equals('8')) substring = "\n\n";
                        }
                        else
                        {
                            if (!readyToCut) substring = substring + input[i];
                        }
                        foundAt = false;
                    }
                    result = result + substring;
                }
                input = result;
                /*
                input = input.Replace("@@@0", "");
                input = input.Replace("@@@1", "");
                input = input.Replace("@@@2", "");
                input = input.Replace("@@@8", "");
                input = input.Replace("@@", "");
                input = input.Replace("@0", "\n");
                input = input.Replace("@1", "\n     ");
                input = input.Replace("@2", "\n          ");
                input = input.Replace("@8", "\n\n");*/
            }
            else
            {
                input = input.Replace("@@", "");
                input = input.Replace("@0", "");
                input = input.Replace("@1", "");
                input = input.Replace("@2", "");
                input = input.Replace("@8", "");
            }

            return input;
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // do some stuff ...
            Globals.terjemahanlamakah = Globals.terjemahansblmnya;
            Globals.nobuku = Globals.nobukusblmnya;
            Globals.nopasal = Globals.nopasalsblmnya;

            // cancel the navigation
            NavigationService.GoBack();
        }

        private void addBookmark(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.bacaan.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            String text = (selectedListBoxItem.Content as AyatAlkitab).ayatAsli;
            int zz = getnoayat(text);
            bacaan.SelectedIndex = zz - 1;
            AyatFull ayat = new AyatFull(Globals.terjemahanlamakah, Globals.nobuku, Globals.nopasal, zz, text);

            if (Globals.bookmarks.Count == 0)
            {
                Globals.bookmarks.Insert(0, ayat);
            }
            else
            {
                int insertAt = 0;
                Boolean same = false;
                for (int i = 0; i < Globals.bookmarks.Count; i++)
                {
                    int compareResult = ayat.CompareTo(Globals.bookmarks[i]);
                    if (compareResult > 0)
                    {
                        insertAt = i + 1;
                    }
                    else if (compareResult < 0)
                    {
                        insertAt = i;
                        break;
                    }
                    else
                    {
                        same = true;
                        break;
                    }
                }
                if (!same) Globals.bookmarks.Insert(insertAt, ayat);
            }
        }

        private void bacaan_GotFocus(object sender, RoutedEventArgs e)
        {
            if (pigiKe.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                pigiKe.Visibility = Visibility.Collapsed;
            }
            if (searchBox.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                searchBox.Visibility = Visibility.Collapsed;
            }
        }

        private void bacaan_Loaded(object sender, RoutedEventArgs e)
        {
            bacaan.ScrollIntoView(bacaan.SelectedItem);
            if (!(bacaan.FontSize == (int)Globals.Settingan["fontsize?"])) bacaan.FontSize = (int)Globals.Settingan["fontsize?"];
            refreshPage();
        }

        private void bacaan_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Globals.noayat = bacaan.SelectedIndex + 1;
            updateHistory();
            if (parallelOn >= 0)
            {
                if (tmp.Count > 0) tmp[parallelOn].removeInfo();
                parallelOn = -1;
            }
        }

        private void berikutnya_Click(object sender, EventArgs e)
        {
            if (Globals.nopasal + 1 <= jumlahPasal())
            {
                Globals.nopasal++;
                getText(ijudul, Globals.nopasal, 1);
                restartBacaan();
                PageTitle.Text = "";
                PageTitle.Text = judul + " " + Globals.nopasal;
            }
            else
            {
                try
                {
                    MessageBox.Show(returnErrorText(true));
                }
                catch (Exception)
                {
                }
            }
        }

        private void BuildApplicationBar()
        {
            ApplicationBar = new ApplicationBar();

            ApplicationBarIconButton backBarButton = new ApplicationBarIconButton(new Uri("Images/ApplicationBar/appbar.back.rest.png", UriKind.Relative));
            backBarButton.Text = Labels.back;
            backBarButton.Click += new EventHandler(sebelumnya_Click);

            ApplicationBarIconButton searchBarButton = new ApplicationBarIconButton(new Uri("Images/ApplicationBar/appbar.feature.search.rest.png", UriKind.Relative));
            searchBarButton.Text = Labels.gotoVerse;
            searchBarButton.Click += new EventHandler(goto_Click);

            ApplicationBarIconButton nextBarButton = new ApplicationBarIconButton(new Uri("Images/ApplicationBar/appbar.next.rest.png", UriKind.Relative));
            nextBarButton.Text = Labels.next;
            nextBarButton.Click += new EventHandler(berikutnya_Click);

            ApplicationBarMenuItem searchTextMenuItem = new ApplicationBarMenuItem(Labels.searchText);
            searchTextMenuItem.Click += new EventHandler(searchBox_Click);
            ApplicationBarMenuItem chgTransMenuItem = new ApplicationBarMenuItem(Labels.changeTranslation);
            chgTransMenuItem.Click += new EventHandler(ganti_Bahasa);
            ApplicationBarMenuItem parReadMenuItem = new ApplicationBarMenuItem(Labels.parallelreading);
            parReadMenuItem.Click += new EventHandler(parallel_Click);
            ApplicationBarMenuItem sendChapterMenuItem = new ApplicationBarMenuItem(Labels.send);
            sendChapterMenuItem.Click += new EventHandler(send_Click);
            ApplicationBarMenuItem tootleTitleMenu = new ApplicationBarMenuItem(Labels.toggleTitle);
            tootleTitleMenu.Click += new EventHandler(sembunyikanJudul_Click);
            ApplicationBarMenuItem changeFontSize = new ApplicationBarMenuItem(Labels.chfontsize);
            changeFontSize.Click += new EventHandler(gantiF_Click);
            

            ApplicationBar.Buttons.Add(backBarButton);
            ApplicationBar.Buttons.Add(searchBarButton);
            ApplicationBar.Buttons.Add(nextBarButton);

            ApplicationBar.MenuItems.Add(searchTextMenuItem);
            ApplicationBar.MenuItems.Add(chgTransMenuItem);
            ApplicationBar.MenuItems.Add(parReadMenuItem);
            ApplicationBar.MenuItems.Add(sendChapterMenuItem);
            ApplicationBar.MenuItems.Add(tootleTitleMenu);
            ApplicationBar.MenuItems.Add(changeFontSize);
        }

        private void comment_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.bacaan.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            String text = (selectedListBoxItem.Content as AyatAlkitab).ayatAsli;
            int zz = getnoayat(text);
            bacaan.SelectedIndex = zz - 1;
            NavigationService.Navigate(new Uri("/View/Comment.xaml", UriKind.Relative));
        }

        private void copy_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.bacaan.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            String text = (selectedListBoxItem.Content as AyatAlkitab).ayatAsli;

            String inhalt = PageTitle.Text + "\n" + text;
            Clipboard.SetText(inhalt);
        }

        private void ganti_Bahasa(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/View/PilihTerjemahan.xaml", UriKind.Relative));
        }

        private void gantiF_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/View/UkuranFont.xaml", UriKind.Relative));
        }
        private int getnoayat(String x)
        {
            int xx = x.IndexOf('(');
            int yy = x.IndexOf(')');
            return Convert.ToInt16(x.Substring(xx + 1, yy - xx - 1));
        }

        private List<String> getParallel(int kk, int pp, int aa)
        {
            List<String> output = new List<string>();
            String[] daftarTerjemahan = { "TerjemahanBaru", "IndonesiaSeharihari", "GermanvLuther", "AmericanStandardVersion", "KingJamesVersion" };
            string k = Convert.ToString(kk);
            string p = Convert.ToString(pp);
            string a = Convert.ToString(aa);
            string tmp2 = "";
            for (int xx = 0; xx < 5; xx++)
            {
                String tempString = Globals.Settingan["parallelRead"] as String;
                if (tempString.Equals("00000")) output.Add(Labels.pleaseEnableParallel);
                if (tempString[xx].Equals('1') && !(Globals.versiKitab.Equals(daftarTerjemahan[xx])))
                {
                    bool found = false;
                    char[] delimiterChars = { '\t' };
                    String tempxx = "Kitab/" + daftarTerjemahan[xx] + "/" + k + ".txt";
                    var rs = Application.GetResourceStream(new Uri(tempxx, UriKind.Relative));
                    bool ayatMazmuzrkah = ((kk == 19) && (daftarTerjemahan[xx].Equals("TerjemahanBaru")));
                    StreamReader inFlow = new StreamReader(rs.Stream);
                    while (!found)
                    {
                        tmp2 = inFlow.ReadLine();
                        if (tmp2 == null) { output.Add(Labels.noVerse); break; }
                        string[] pecahan = tmp2.Split(delimiterChars);
                        if (pecahan[2].Equals(p))
                        {
                            if (pecahan[3].Equals(a))
                            {
                                output.Add("\n\n[" + daftarTerjemahan[xx] + "]");
                                if (ayatMazmuzrkah) output.Add(prosesMazmurAyat(pecahan[4])); else output.Add(pecahan[4]);
                                found = true;
                            }
                        }
                    }
                }
            }
            return output;
        }

        private void getText(int kk, int pp, int aa)
        {
            tmp.Clear();
            string k = Convert.ToString(kk);
            string p = Convert.ToString(pp);
            string a = Convert.ToString(aa);
            x = 0;
            string tmp2 = "";
            bool startRead = false;
            bool endRead = false;
            bool ayatMazmurkah = ((kk == 19) && (Globals.versiKitab.Equals("TerjemahanBaru")));
            char[] delimiterChars = { '\t' };
            String tempxx = "Kitab/" + Globals.versiKitab + "/" + k + ".txt";
            var rs = Application.GetResourceStream(new Uri(tempxx, UriKind.Relative));
            StreamReader inFlow = new StreamReader(rs.Stream);
            while (startRead == false)
            {
                tmp2 = inFlow.ReadLine();

                string[] pecahan = tmp2.Split(delimiterChars);
                if (pecahan[2].Equals(p))
                {
                    if (pecahan[3].Equals(a))
                    {
                        startRead = true;
                        if (ayatMazmurkah) { tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + prosesMazmurAyat(pecahan[4]))); } else tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + pecahan[4]));
                        x++;
                    }
                }
            }

            while (endRead == false)
            {
                tmp2 = inFlow.ReadLine();
                if (tmp2 == null) { endRead = true; break; }
                string[] pecahan = tmp2.Split(delimiterChars);
                if (!(pecahan[2].Equals(p))) { endRead = true; break; }
                if (ayatMazmurkah) { tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + prosesMazmurAyat(pecahan[4]))); } else tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + pecahan[4]));
                x++;
            }
        }

        private ObservableCollection<AyatAlkitab> getText(int kk, int pp, int aa, bool trigger)
        {
            ObservableCollection<AyatAlkitab> tmp = new ObservableCollection<AyatAlkitab>();
            tmp.Clear();
            string k = Convert.ToString(kk);
            string p = Convert.ToString(pp);
            string a = Convert.ToString(aa);
            x = 0;
            string tmp2 = "";
            bool startRead = false;
            bool endRead = false;
            bool ayatMazmuzrkah = ((kk == 19) && (Globals.versiKitab.Equals("TerjemahanBaru")));
            char[] delimiterChars = { '\t' };
            String tempxx = "Kitab/" + Globals.versiKitab + "/" + k + ".txt";
            var rs = Application.GetResourceStream(new Uri(tempxx, UriKind.Relative));
            StreamReader inFlow = new StreamReader(rs.Stream);
            while (startRead == false)
            {
                tmp2 = inFlow.ReadLine();

                string[] pecahan = tmp2.Split(delimiterChars);
                if (pecahan[2].Equals(p))
                {
                    if (pecahan[3].Equals(a))
                    {
                        startRead = true;
                        if (ayatMazmuzrkah) { tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + prosesMazmurAyat(pecahan[4]))); } else tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + pecahan[4]));
                        x++;
                    }
                }
            }

            while (endRead == false)
            {
                tmp2 = inFlow.ReadLine();
                if (tmp2 == null) { endRead = true; break; }
                string[] pecahan = tmp2.Split(delimiterChars);
                if (!(pecahan[2].Equals(p))) { endRead = true; break; }
                if (ayatMazmuzrkah) { tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + prosesMazmurAyat(pecahan[4]))); } else tmp.Add(new AyatAlkitab("(" + pecahan[3] + ") " + pecahan[4]));
                x++;
            }

            return tmp;
        }

        private void goto_Click(object sender, EventArgs e)
        {
            if (pigiKe.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                pigiKe.Visibility = Visibility.Collapsed;
            }
            else
            {
                bacaan.Margin = new Thickness(12, 6, 6, 81);
                pigiKe.Visibility = Visibility.Visible;
            }
            if (searchBox.Visibility == Visibility.Visible)
            {
                searchBox.Visibility = Visibility.Collapsed;
            }
        }

        private void initializePage()
        {
            ObservableCollection<AyatAlkitab> blabla = getText(ijudul, Globals.nopasal, 1, true);
            Dispatcher.BeginInvoke(delegate
            {
                tmp = blabla;
                bacaan.ItemsSource = tmp;
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    if (Globals.noayat == 0)
                    {
                        bacaan.SelectedIndex = 0;
                    }
                    else
                    {
                        bacaan.SelectedIndex = Globals.noayat - 1;
                    }
                    progressbar.Visibility = Visibility.Collapsed;
                    progressbar.IsIndeterminate = false;
                });
            });
        }

        private string intxstr(int x)
        {
            string tmp = Convert.ToString(x);
            int y = tmp.Length;
            for (int i = y; i <= 4; i++)
            {
                tmp = tmp.Insert(0, "0");
            }

            return tmp;
        }

        private int jumlahAyat()
        {
            return tmp.Count;
        }

        //        pigiKe.Focus();
        private int jumlahPasal()
        {
            if (Globals.terjemahanlamakah)
            {
                switch (Globals.nobuku)
                {
                    case 1: return 50;
                    case 2: return 40;
                    case 3: return 27;
                    case 4: return 36;
                    case 5: return 34;
                    case 6: return 24;
                    case 7: return 21;
                    case 8: return 4;
                    case 9: return 31;
                    case 10: return 24;
                    case 11: return 22;
                    case 12: return 25;
                    case 13: return 29;
                    case 14: return 36;
                    case 15: return 10;
                    case 16: return 13;
                    case 17: return 10;
                    case 18: return 42;
                    case 19: return 150;
                    case 20: return 31;
                    case 21: return 12;
                    case 22: return 8;
                    case 23: return 66;
                    case 24: return 52;
                    case 25: return 5;
                    case 26: return 48;
                    case 27: return 12;
                    case 28: return 14;
                    case 29: return 3;
                    case 30: return 9;
                    case 31: return 1;
                    case 32: return 4;
                    case 33: return 7;
                    case 34: return 3;
                    case 35: return 3;
                    case 36: return 3;
                    case 37: return 2;
                    case 38: return 14;
                    case 39: return 4;
                    default: return 0;
                }
            }
            else
            {
                switch (Globals.nobuku)
                {
                    case 1: return 28;
                    case 2: return 16;
                    case 3: return 24;
                    case 4: return 21;
                    case 5: return 28;
                    case 6: return 16;
                    case 7: return 16;
                    case 8: return 13;
                    case 9: return 6;
                    case 10: return 6;
                    case 11: return 4;
                    case 12: return 4;
                    case 13: return 5;
                    case 14: return 3;
                    case 15: return 6;
                    case 16: return 4;
                    case 17: return 3;
                    case 18: return 1;
                    case 19: return 13;
                    case 20: return 5;
                    case 21: return 5;
                    case 22: return 3;
                    case 23: return 5;
                    case 24: return 1;
                    case 25: return 1;
                    case 26: return 1;
                    case 27: return 22;
                    default: return 0;
                }
            }
        }

        private void MaskNumericInput(TextBox textBoxControl)
        {
            char[] validChars = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };

            Boolean continuex = false;

            if (textBoxControl.Text.Length > 0)
            {
                if (textBoxControl.Text[0].Equals('0')) continuex = false;
                else
                {
                    foreach (char s in validChars)
                    {
                        if (textBoxControl.Text.Length > 0)
                        {
                            if (textBoxControl.Text[textBoxControl.Text.Length - 1].Equals(s))
                            {
                                continuex = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (!(continuex))
            {
                if (textBoxControl.Text.Length > 0)
                {
                    textBoxControl.Text = textBoxControl.Text.Substring(0, textBoxControl.Text.Length - 1);
                    bacaan.Focus();
                }
            }
        }

        private void parallel_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/View/ParallelRead.xaml", UriKind.Relative));
        }

        private void parallel1_Click(object sender, RoutedEventArgs e)
        {
            ListBoxItem selectedListBoxItem = this.bacaan.ItemContainerGenerator.ContainerFromItem((sender as MenuItem).DataContext) as ListBoxItem;

            String text = (selectedListBoxItem.Content as AyatAlkitab).ayatAsli;
            int zz = getnoayat(text);
            List<String> temporar = getParallel(ijudul, Globals.nopasal, zz);
            foreach (String i in temporar)
            {
                tmp[zz - 1].addInfo(i);
            }
            bacaan.ItemsSource = null;
            bacaan.ItemsSource = tmp;
            bacaan.SelectedIndex = zz - 1;
            parallelOn = zz - 1;
        }

        private void pigiKe_GotFocus(object sender, RoutedEventArgs e)
        {
            if (pigiKe.Text == Labels.textBox_InputVerse)
            {
                pigiKe.Text = "";
                SolidColorBrush Brush1 = new SolidColorBrush();
                Brush1.Color = Colors.Black;
                pigiKe.Foreground = Brush1;
            }
        }

        private void pigiKe_KeyUp(object sender, KeyEventArgs e)
        {
            MaskNumericInput((TextBox)sender);

            if ((!(pigiKe.Text.Equals(Labels.textBox_InputVerse))) & (!(pigiKe.Text.Equals(""))) & (!(pigiKe.Text == null)))
            {
                int inputtedNumber = Convert.ToInt16(pigiKe.Text);

                if (jumlahAyat() < inputtedNumber)
                {
                    MessageBox.Show(returnErrorSearch());
                    pigiKe.Text = pigiKe.Text.Remove(pigiKe.Text.Length - 1);
                    pigiKe.SelectionStart = pigiKe.Text.Length;
                }
                else
                    bacaan.SelectedIndex = Convert.ToInt16(pigiKe.Text) - 1;
            }
        }

        private void pigiKe_LostFocus(object sender, RoutedEventArgs e)
        {
            pigiKe.Text = Labels.textBox_InputVerse;
            SolidColorBrush Brush2 = new SolidColorBrush();
            Brush2.Color = Colors.Gray;
            pigiKe.Foreground = Brush2;

            if (pigiKe.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                pigiKe.Visibility = Visibility.Collapsed;
            }
        }

        private void refreshPage()
        {
            if (needRefresh)
            {
                if ((int)Globals.Settingan["judulvisible?"] == 0) PageTitle.Visibility = Visibility.Collapsed; else PageTitle.Visibility = Visibility.Visible;

                System.Threading.Thread startupThread =
                 new System.Threading.Thread(new System.Threading.ThreadStart(initializePage));
                startupThread.Start();

                judul = "";
                if (Globals.terjemahanlamakah) judul = Globals.daftarBukuA[Globals.nobuku - 1]; else judul = Globals.daftarBukuN[Globals.nobuku - 1];
                PageTitle.Text = "";
                PageTitle.Text = judul + " " + Globals.nopasal;

                needRefresh = false;
            }
        }

        private void restartBacaan()
        {
            if (pigiKe.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                pigiKe.Visibility = Visibility.Collapsed;
            }
            if (searchBox.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                searchBox.Visibility = Visibility.Collapsed;
            }
            bacaan.SelectedIndex = 0;
            updateHistory();
        }

        private string returnErrorSearch()
        {
            if ((int)Globals.Settingan["languagek?"] == 1)
            {
                return ("Mohon masukan nomor ayat yang benar.\n" + PageTitle.Text + " hanya mempunyai " + jumlahAyat() + " ayat.");
            }
            else
            {
                if ((int)Globals.Settingan["languagek?"] == 2)
                {
                    return ("Please enter a valid verse.\n" + PageTitle.Text + " has only " + jumlahAyat() + " verses.");
                }

                else
                {
                    return ("Bitte eine gueltige Versnummer eingeben.\n" + PageTitle.Text + " hat nur " + jumlahAyat() + " Verse.");
                }
            }
        }

        private string returnErrorSearch2()
        {
            if ((int)Globals.Settingan["languagek?"] == 1)
            {
                return ("Frase atau kata \"" + searchBox.Text + "\" tidak terdapat pada halaman ini. Silakan coba lagi kata atau frase yang lain.");
            }
            else
            {
                if ((int)Globals.Settingan["languagek?"] == 2)
                {
                    return ("The text \"" + searchBox.Text + "\" does not exist in this page. Please try again with another text.");
                }

                else
                {
                    return ("Der Text \"" + searchBox.Text + "\" existiert auf dieser Seite nicht. Bitte mit anderem Text es nochmal versuchen.");
                }
            }
        }

        private string returnErrorText(Boolean nextone)
        {
            if (nextone) return (Labels.MSG_CantNext + judul + "\".");
            else
                return (Labels.MSG_CantBack + judul + "\".");
        }

        private void searchBox_Click(object sender, EventArgs e)
        {
            if (searchBox.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                searchBox.Visibility = Visibility.Collapsed;
            }
            else
            {
                bacaan.Margin = new Thickness(12, 6, 6, 81);
                searchBox.Visibility = Visibility.Visible;
            }
            if (pigiKe.Visibility == Visibility.Visible)
            {
                pigiKe.Visibility = Visibility.Collapsed;
            }
        }

        private void searchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (searchBox.Text == Labels.textBox_InputText)
            {
                searchBox.Text = "";
                SolidColorBrush Brush1 = new SolidColorBrush();
                Brush1.Color = Colors.Black;
                searchBox.Foreground = Brush1;
            }
        }

        private void searchBox_KeyUp(object sender, KeyEventArgs e)
        {
            //MaskNumericInput((TextBox)sender);
            if (e.Key == Key.Enter)
            {
                if (matchedIndex.Contains(bacaan.SelectedIndex) && !(matchedIndex == null))
                {
                    int y = matchedIndex.IndexOf(bacaan.SelectedIndex);
                    if ((y + 1) == matchedIndex.Count)
                        bacaan.SelectedIndex = matchedIndex[0];
                    else
                        bacaan.SelectedIndex = matchedIndex[y + 1];
                }
            }
            else
                if ((!(searchBox.Text.Equals(Labels.textBox_InputText))) & (!(searchBox.Text.Equals(""))) & (!(searchBox.Text == null)))
                {
                    try
                    {
                        int inputtedNumber = Convert.ToInt16(searchBox.Text);

                        if (jumlahAyat() < inputtedNumber)
                        {
                            MessageBox.Show(returnErrorSearch());
                            searchBox.Text = searchBox.Text.Remove(searchBox.Text.Length - 1);
                            searchBox.SelectionStart = searchBox.Text.Length;
                        }
                        else
                            bacaan.SelectedIndex = Convert.ToInt16(searchBox.Text) - 1;
                    }
                    catch (FormatException)
                    {
                        matchedIndex = new ObservableCollection<int>();
                        for (int i = 0; i < tmp.Count; i++)
                        {
                            if (tmp[i].ayatAsli.ToLower().Trim().Contains(searchBox.Text.ToLower().Trim()))
                            {
                                matchedIndex.Add(i);
                            }
                        }

                        if (matchedIndex.Count < 1)
                        {
                            MessageBox.Show(returnErrorSearch2());
                            searchBox.Text = searchBox.Text.Remove(searchBox.Text.Length - 1);
                            searchBox.SelectionStart = searchBox.Text.Length;
                        }
                        else
                            bacaan.SelectedIndex = matchedIndex[0];
                    }
                }
        }

        private void searchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            searchBox.Text = Labels.textBox_InputText;
            SolidColorBrush Brush2 = new SolidColorBrush();
            Brush2.Color = Colors.Gray;
            searchBox.Foreground = Brush2;

            if (searchBox.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                searchBox.Visibility = Visibility.Collapsed;
            }
        }

        private void sebelumnya_Click(object sender, EventArgs e)
        {
            if (Globals.nopasal - 1 > 0)
            {
                Globals.nopasal--;
                getText(ijudul, Globals.nopasal, 1);
                restartBacaan();

                PageTitle.Text = "";
                PageTitle.Text = judul + " " + Globals.nopasal;
            }
            else
            {
                try
                {
                    MessageBox.Show(returnErrorText(false));
                }
                catch (Exception)
                {
                }
            }
        }

        private void sembunyikanJudul_Click(object sender, EventArgs e)
        {
            if (pigiKe.Visibility == Visibility.Visible)
            {
                bacaan.Margin = new Thickness(12, 6, 6, 6);
                pigiKe.Visibility = Visibility.Collapsed;
            }
            if (PageTitle.Visibility == Visibility.Visible)
            {
                PageTitle.Visibility = Visibility.Collapsed;
                Globals.Settingan["judulvisible?"] = 0;
            }
            else
            {
                PageTitle.Visibility = Visibility.Visible;
                Globals.Settingan["judulvisible?"] = 1;
            }
        }

        private void send_Click(object sender, EventArgs e)
        {
            String inhalt = verfasText();
            EmailComposeTask emailComposeTask = new EmailComposeTask();
            emailComposeTask.Body = inhalt;
            emailComposeTask.Show();
        }

        private void updateHistory()
        {
            if (!Globals.stopupdatinghistory)
            {
                if (bacaan.SelectedIndex > -1)
                {
                    if (Globals.history.Count > 25) Globals.history.RemoveAt(25);
                    if ((Globals.history.Count > 0) & (Globals.dunnawhhattonameit)) Globals.history.RemoveAt(0);
                    Globals.dunnawhhattonameit = true;
                    AyatFull ayat = new AyatFull(Globals.terjemahanlamakah, Globals.nobuku, Globals.nopasal, Globals.noayat, tmp[bacaan.SelectedIndex].ayatAsli);

                    //Globals.history.Insert(0,xxxx + "|" + Globals.nobuku + "|" + pasalke + "|" + Alkitab.Pilihan.noayat + "|" + tmp[bacaan.SelectedIndex].ayatAsli);
                    Globals.history.Insert(0, ayat);
                }
            }
        }

        private String verfasText()
        {
            String result = "";
            result += PageTitle.Text;
            result += "\n";
            foreach (AyatAlkitab i in tmp)
            {
                result += i.ayatAsli + "\n";
            }
            return result;
        }

        private int verseLenghvontmp()
        {
            for (int x = 0; x <= 180; x++)
            {
                if (tmp[x] == null) return (x);
            }

            return 180;
        }

        private void visibleback()
        {
            if ((int)Globals.Settingan["judulvisible?"] == 0) PageTitle.Visibility = Visibility.Collapsed; else PageTitle.Visibility = Visibility.Visible;
            bacaan.Visibility = Visibility.Visible;
            getText(ijudul, Globals.nopasal, 1);
            bacaan.SelectedIndex = Globals.noayat;
            judul = "";
            if (Globals.terjemahanlamakah) judul = Globals.daftarBukuA[Globals.nobuku - 1]; else judul = Globals.daftarBukuN[Globals.nobuku - 1];
            PageTitle.Text = "";
            PageTitle.Text = judul + " " + Globals.nobuku;
        }

        #endregion Methods
    }
}